import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../config/color_config.dart';
import 'common.dart';
import 'package:example/utils/file_ext.dart';

class UserHandleManager {

  // static final UserHandleManager _singleton = UserHandleManager._internal();
  //
  // String? serviceTelStr;
  //
  // factory UserHandleManager() {
  //   return _singleton;
  // }
  //
  // UserHandleManager._internal();
  //
  // static UserHandleManager getInstance() {
  //   return UserHandleManager();
  // }

  ///去相册中选择照片

  /// 打开相册
  Future<List<AssetEntity>?> openPhotos<T>(
      {List<AssetEntity>? selectedAssets,
        RequestType type = RequestType.image,
        maxCount = 1}) async {

    bool pStatus = await checkPhotoPermission();
    if(pStatus == false){
      return Future.error("请打开相册权限后重试");
    }

    return AssetPicker.pickAssets(
      getCurContext(),
      pickerConfig: AssetPickerConfig(
        maxAssets: maxCount,
        requestType: type,
        themeColor: ColorConfig.main,
        selectedAssets: selectedAssets,
        pathNameBuilder: Platform.isAndroid ? (AssetPathEntity path)  {
          if(path.name == 'Camera'){
            return '相机';
          }else if(path.name == 'WeiXin'){
            return '微信';
          }else if(path.name == 'Screenshots'){
            return '截屏';
          }else if(path.name == 'Recent'){
            return '最近';
          }else{
            return path.name;
          }
        }:null,
      ),
    ).catchError((e) {
      showToast("openPhotos:$e");
    });
  }

  ///打开相机
  Future<AssetEntity?> openCamera(RequestType type,{BuildContext? context}) async {
    if (type == RequestType.image || type == RequestType.video) {
      bool pStatus = await checkCameraPermission();
      if(pStatus == false){
        return Future.error("请打开相机权限后重试");
      }
    }

    try {
      if (type == RequestType.image) {
        return (await CameraPicker.pickFromCamera(context ?? getCurContext()));

      } else if (type == RequestType.video) {
        return (await ImagePicker().pickVideo(source: ImageSource.camera))
            ?.toFile()
            .toAssetEntity()
            .catchError((e) {
          showToast("openCamera:$e");
        });
      }
    } catch (e) {
      // showToast("openCamera:catch -> $e");
      print('====image===$e');
      // if(type == RequestType.image){
      //   return (await CameraPicker.pickFromCamera(getCurContext()));
      // }
    }
    return null;
  }

  ///获取相册权限
  Future<bool> checkPhotoPermission() async {

    if(Platform.isAndroid){

      DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;

      int myAndroidAPILevel = androidInfo.version.sdkInt;
      print('=APILevel=$myAndroidAPILevel');
      if(myAndroidAPILevel >= 33){// Android 13及以上请求相册权限
        Map<Permission, PermissionStatus> status = await [Permission.photos].request();
        if (status[Permission.photos]?.isDenied == true ||
            status[Permission.photos]?.isPermanentlyDenied == true) {
          print('===${status[Permission.photos]?.isDenied}===${status[Permission.photos]?.isPermanentlyDenied}');
          showToast("请打开相册权限后重试");
          return false;
          // return Future.error("请打开相册权限后重试");
        }
      }else {
        Map<Permission, PermissionStatus> status = await [Permission.storage].request();
        if (status[Permission.storage]?.isDenied == true ||
            status[Permission.storage]?.isPermanentlyDenied == true) {
          print('===${status[Permission.storage]?.isDenied}===${status[Permission.storage]?.isPermanentlyDenied}');
          showToast("请打开存储权限后重试");
          return false;
          // return Future.error("请打开存储权限后重试");
        }
      }

    }else{
      PermissionStatus status = await Permission.photos.request();
      if (status.isDenied == true ||
          status.isPermanentlyDenied == true) {
        showToast("请打开相册权限后重试");
        return false;
        // return Future.error("请打开相册权限后重试");
      }
    }
    return true;
  }

  ///获取相机权限
  Future<bool> checkCameraPermission() async{

    if(Platform.isAndroid){

      DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      int myAndroidAPILevel = androidInfo.version.sdkInt;
      List<Permission> checkList = [];
      if(myAndroidAPILevel >= 33){
        checkList = [
          Permission.camera,
          Permission.photos,
        ];
      }else{
        checkList = [
          Permission.camera,
          Permission.storage,
        ];
      }

      Map<Permission, PermissionStatus> status = await checkList.request();

      if(myAndroidAPILevel >= 33){
        if (status[Permission.camera]?.isDenied == true ||
            status[Permission.camera]?.isPermanentlyDenied == true) {
          showToast("请在设置中打开相机权限后重试");
          return Future.error("请打开相机权限后重试");
        }else if (status[Permission.photos]?.isDenied == true ||
            status[Permission.photos]?.isPermanentlyDenied == true) {
          showToast("请打开相册权限后重试");
          return Future.error("请打开相册权限后重试");
        }
      }else{
        if (status[Permission.camera]?.isDenied == true ||
            status[Permission.camera]?.isPermanentlyDenied == true) {
          showToast("请在设置中打开相机权限后重试");
          return Future.error("请打开相机权限后重试");
        } else if (status[Permission.storage]?.isDenied == true ||
            status[Permission.storage]?.isPermanentlyDenied == true) {
          showToast("请在设置中打开存储权限后重试");
          return Future.error("请打开存储权限后重试");
        }
      }

    }else{
      Map<Permission, PermissionStatus> status = await [
        Permission.camera,
        Permission.photos,
      ].request();
      if (status[Permission.camera]?.isDenied == true ||
          status[Permission.camera]?.isPermanentlyDenied == true) {
        showToast("请在设置中打开相机权限后重试");
        return Future.error("请打开相机权限后重试");
      } else if (status[Permission.photos]?.isDenied == true||
          status[Permission.photos]?.isPermanentlyDenied == true) {
        showToast("请在设置中打开相册权限后重试");
        return Future.error("请打开相册权限后重试");
      }
    }

    return true;
  }

}